package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketAddress;
import com.cskaoyan.market.service.MarketAdminAddressService;
import com.cskaoyan.market.service.impl.MarketAdminAdminAddressServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/address/*")
public class AdminAddressController extends HttpServlet {
    MarketAdminAddressService marketAdminAddressService = new MarketAdminAdminAddressServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace("/admin/address/", "");

        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /**
         * 参数解析
         */
        String pageStr = req.getParameter("page");
        String limitStr = req.getParameter("limit");
        String name = req.getParameter("name");
        String userIdStr = req.getParameter("userId");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");

        /**
         * 参数校验
         */
        int page = 0;
        int limit = 0;
        Integer userId;

        // userId可以为空，若转型失败应捕捉异常，赋值为null
        try {
            userId = Integer.parseInt(userIdStr);
        } catch (NumberFormatException e) {
            userId = null;
        }

        // page、limit均不得为空--为空则往请求体写入错误信息，结束方法
        try {
            page = Integer.parseInt(pageStr);
            limit = Integer.parseInt(limitStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resp.getWriter().println(
                    JacksonUtil.writeValueAsString(
                            ResponseUtil.badArgumentValue()
                    )
            );
            return;
        }

        // sort、order不得为空--设置缺省值
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }

        /**
         * 通过校验，调用service层
         */
        List<MarketAddress> marketAddressList = marketAdminAddressService.list(page, limit, name, userId, sort, order);

        /**
         * 设置响应体
         */
        // 将对象通过工具类完善并转换为json字符串
        resp.getWriter().println(
                JacksonUtil.writeValueAsString(
                        ResponseUtil.okList(marketAddressList)
                )
        );

    }
}
